import React, { Component } from "react";
import { connect } from "react-redux";
import { Toast, InputItem, Button, Modal } from "antd-mobile";
import yhTools from "@/tools/yh";
import MainLayout from "@/component/mainLayout/mainLayout";
import { InterfaceG } from "@/config/Config";

import "./AuthenticatePayCode.scss";

class AuthenticatePayCode extends Component {
	constructor(props) {
		super(props);
		this.state = {
			phoneValue: "",
			yzmValue: "",
			selectFlag: false,
			timeText: "获取验证码",
			time: 60,
			messageSerialNumber: "", // 银行短信流水号
			messageModal: false, //错误提示弹出框
			errorMeassge: ""
		};
		this.timer = null;
		this.isOpen = true;
		let params = JSON.parse(this.props.match.params.data);
		this.channelCode = params.channelCode;
		this.amount = params.amount;
		this.goBackIndex = params.goBackIndex;
		this._pagetype = props.location.pathname.indexOf("xhb") === -1 ? 0 : 1;
	}

	componentDidMount() {}

	componentWillUnmount() {
		clearInterval(this.timer);
	}

	changeyzm(yzmValue) {
		this.setState({ yzmValue });
	}

	//倒计时
	countdown() {
		this.isOpen = false;
		const _that = this;
		let { time } = this.state;
		this.timer = setInterval(() => {
			if (time < 1) {
				clearInterval(this.timer);
				this.isOpen = true;
				_that.setState({
					time: 60,
					timeText: "重新获取"
				});
			} else {
				time--;
				_that.setState({
					time,
					timeText: `${time}秒`
				});
			}
		}, 1000);
	}

	// 协议签约重获取验证码接口
	getVerifyCode() {
		if (!this.isOpen) {
			return;
		}
		let objs = {
			url: InterfaceG.eleRechargeSendSms,
			params: {
				channelCode: this.channelCode
			},
			_alertShow: false
		};
		// console.log("---getVerifyCode---", objs);
		Toast.loading("正在提交中...", 100, () => {});
		yhTools
			.request(objs)
			.then(res => {
				Toast.hide();
				const data = res.data;
				if (res.code === "0") {
					this.countdown();
					this.setState({
						messageSerialNumber: data.messageSerialNumber,
						payRouteCode: data.payRouteCode,
						openId: data.openId
					});
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}

	/**
	 * 充值
	 */
	reChargeAction() {
		const { yzmValue, messageSerialNumber } = this.state;
		if (!messageSerialNumber) {
			Toast.info("请先获取验证码");
			return false;
		}
		if (!yzmValue) {
			Toast.info("请输入验证码");
			return false;
		}
		if (yzmValue.length < 6) {
			Toast.info("请输入正确的验证码");
			return false;
		}
		const params = {
			url: InterfaceG.eleRecharge,
			params: {
				channelCode: this.channelCode, // 渠道编码
				amount: this.amount, // 充值金额
				messageSerialNumber: messageSerialNumber, // 银行短信流水号
				activeCode: yzmValue // 短信验证码
			},
			_alertShow: false
		};
		Toast.loading("正在充值中...", 100, () => {});
		yhTools
			.request(params)
			.then(res => {
				Toast.hide();
				if (res.code === "0") {
					/**
					 * 如果是原生进入充值界面,index_fromType = app
					 * 充值成功后需要调用原生方法关闭页面
					 */
					let index_fromType = sessionStorage.getItem("index_fromType");
					if (index_fromType && index_fromType === "app") {
						yhTools.closePage();
					} else {
						Modal.alert("充值处理中", "充值处理中，请稍后查看账户记录", [
							{
								text: "我知道了",
								onPress: () => {
									this.props.history.go(this.goBackIndex);
								}
							}
						]);
					}
				} else if (res.code === "00033") {
					this.setState({
						errorMeassge: res.message,
						messageModal: true
					});
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}
	handleCall = () => {
		let callPhoneData = {
			telphone: "4008219666"
		};
		yhTools.callPhone(callPhoneData);
	};
	render() {
		const headerParams = {
			header: {
				title: "充值"
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles,
			loadStatus: this.state.loadStatus // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
		};
		return (
			<MainLayout pageParams={headerParams}>
				<div className="AuthenticatePayCodePage">
					<div className="card">
						<div className="card-r">
							<p className="card-name">充值金额</p>
							<p className="card-number">{this.amount}</p>
						</div>
					</div>
					<ul className="info info-input">
						<li className="yzm-box" ref="zym">
							<InputItem
								maxLength={6}
								type="number"
								placeholder="请输入短信验证码"
								onChange={this.changeyzm.bind(this)}
								value={this.state.yzmValue}
							>
								验证码
							</InputItem>
							<div className="info-yzm" onClick={this.getVerifyCode.bind(this)}>
								{this.state.timeText}
							</div>
						</li>
					</ul>
					<div className="btn">
						<Button onClick={this.reChargeAction.bind(this)} type="primary">
							确认充值
						</Button>
					</div>
					<Modal
						visible={this.state.messageModal}
						transparent
						maskClosable={false}
						onClose={() => {
							this.setState({ messageModal: false });
						}}
						footer={[
							{
								text: "关闭",
								onPress: () => {
									this.setState({ messageModal: false });
								}
							},
							{ text: "拨打电话", onPress: () => this.handleCall() }
						]}
					>
						<div className="error-message-modal">
							<p>{this.state.errorMeassge}</p>
						</div>
					</Modal>
				</div>
			</MainLayout>
		);
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps() {
	return {};
}

export default connect(
	mapStateToProps,
	mapDispatchToProps
)(AuthenticatePayCode);
